
import streamlit as st
from logparse.log_parse import LogParser
from pathlib import Path
from logparse.analyze import analyze


@st.cache_data
def load_last_lines(log_file):
    line_count = 0
    with open(log_file, 'rb') as fs:
        fs.seek(-2, 2)
        while True:
            byte = fs.read(1)
            if byte != b'\n':
                fs.seek(-2, 1)
            else:
                line_count += 1
                if line_count == 30:
                    break
                fs.seek(-2, 1)
        last_lines = fs.readlines()
    last_texts = ''.join([line.decode('utf-8') for line in last_lines])
    return last_texts


def main():
    log_file = Path(__file__).parent.parent / 'logs' / 'debug.log'
    parser = LogParser(log_file)

    with open(log_file, "rb") as fs:
        st.sidebar.download_button(
            label='日志下载',
            data=fs,
            file_name='debug.log',
            mime="log"
        )

    showlog = st.sidebar.button("显示日志")
    if showlog:
        st.text(load_last_lines(log_file))

    # 选择合同数据
    input_datas = parser.get_input_datas()
    files = {data['fileId']: data['documentName'] for data in input_datas}
    option = st.sidebar.radio("选择数据", files.items())
    input_data = parser.find_data_by_id(input_datas, option[0])

    if not showlog:
        analyze(parser, input_data)


if __name__ == "__main__":
    main()